<template>
  <div class="main-eqt-wrapper">
    <div class="copypermis">
      <div class="title befornline">基础配置</div>
      <a-form :model="formData" ref="formRef" layout="vertical" :rules="rules" class="form">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入名称" allowClear />
        </a-form-item>
        <a-form-item label="自编码" name="code">
          <a-input v-model:value="formData.code" placeholder="请输入自编码" allowClear />
        </a-form-item>
        <a-form-item label="设备分类" name="category_id">
          <a-select allowClear placeholder="请选择设备分类" v-model:value="formData.category_id">
            <a-select-option
              v-for="(item, index) in eqtClassOptions"
              :key="index"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-item>

        <a-form-item label="停用">
          <a-switch
            v-model:checked="formData.disable"
            checkedValue="1"
            unCheckedValue="0"
            v-if="isreload"
          />
        </a-form-item>

        <a-form-item label="设备标签" name="tag_list">
          <tags @ok="(e) => tagsOk(e)" :taglist="formData.tag_list" v-if="isreload" />
        </a-form-item>

        <a-form-item name="bg_img">
          <template #label
            >图片 <span class="img-subtile"> (支持jpg、png，建议尺寸500px*500px) </span></template
          >
          <uploadimg @sendIMGInfo="sendIMGInfo" :bgimg="formData.bg_img" v-if="isreload" />
        </a-form-item>
      </a-form>
      <selectSubDevice ref="selectSubDevice" @selectChange="selectChange" />
      <div class="zwf"></div>
      <div class="flex-btn">
        <a-button @click.stop="cancel">取消</a-button>
        <a-button class="cancelBtn" type="primary" @click.stop="handleOk">保存</a-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, Ref, reactive, onMounted, nextTick } from 'vue';
  import uploadimg from '../../components/uploadimg.vue';
  import tags from '/@/components/Form/src/components/tags.vue';
  import { alleqtClass } from '/@/api/sys/brand/brand';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';
  import {
    AddMainEquipmentList,
    ModifyMainEquipmentList,
    GetMainEquipmentDetail,
  } from '/@/api/sys/gateway/gateway';
  import selectSubDevice from './selectSubDevice/index.vue';
  export default defineComponent({
    components: { tags, uploadimg, selectSubDevice },
    emits: ['success'],
    setup() {
      const { createMessage } = useMessage();
      const selectSubDevice = ref();
      const eqtClassOptions: Ref<any[]> = ref([]);
      const router = useRouter();
      const titleType = ref('add');
      const formRef = ref();
      const spinning = ref<boolean>(false);

      //上传图片回调
      function sendIMGInfo(img_url) {
        formData.bg_img = img_url;
      }
      //编辑标签
      function tagsOk(e) {
        formData.tag_list = e;
      }

      //表单数据
      const formData: any = reactive({
        code: '',
        name: '',
        category_id: '',
        disable: '1',
        tag_list: [],
        sub_device_id_list: [],
        bg_img: '',
        device_serial: '',
      });

      //获取选择的的子设备
      const selectChange = (data) => {
        let list: any[] = [...data];
        let subidList: number[] = [];
        list.forEach((item: any) => {
          subidList.push(item.id);
        });
        formData.sub_device_id_list = [];
        formData.sub_device_id_list = subidList;
      };

      //表单验证
      let rules = {
        name: {
          required: true,
          message: '请输入名称',
        },
        code: {
          required: true,
          message: '请输入自编码',
        },
      };
      const isreload = ref(true);
      //获取编辑详情
      async function getediteDetail(id) {
        spinning.value = true;
        GetMainEquipmentDetail({
          id: id,
        }).then((res: any) => {
          isreload.value = false;
          let record: any = res;
          formData.code = record.code;
          formData.name = record.name;
          formData.tag_list = record.tag_list ? record.tag_list : [];
          formData.category_id = record.category_id;
          formData.disable = record.disable === 0 ? record.disable.toString() : '1';
          formData.bg_img = record.bg_img;
          formData.id = record.id;
          formData.device_serial = record.device_serial;
          formData.sub_device_id_list = [];
          if (record.tag_group.length > 0) {
            let tag_list: string[] = [];
            record.tag_group.map((item: any) => {
              tag_list.push(item.tag_name);
            });
            formData.tag_list = tag_list;
          }
          if (record.sub_devices.length > 0) {
            let table_list: any[] = [];
            record.sub_devices.map((item) => {
              formData.sub_device_id_list.push(item.sub_device_id);
            });
            table_list = record.sub_devices;
            nextTick(() => {
              selectSubDevice.value.setrightdataSource(table_list);
            });
          } else {
            nextTick(() => {
              selectSubDevice.value.setrightdataSource([]);
            });
          }
          nextTick(() => {
            spinning.value = false;
            isreload.value = true;
          });
        });
      }

      //保存
      const handleOk = () => {
        if (formData.sub_device_id_list.length == 0) {
          createMessage.warning('请选择子设备');
          return false;
        }
        formRef.value
          .validate()
          .then(() => {
            let obj = formData;
            if (obj.coefficient == '') {
              delete obj.coefficient;
            }
            if (obj.port == '') {
              obj.port = null;
            }
            if (titleType.value == 'edite') {
              ModifyMainEquipmentList(obj).then(() => {
                cancel();
                createMessage.success('编辑成功');
              });
            } else {
              AddMainEquipmentList(obj).then(() => {
                cancel();
                createMessage.success('保存成功');
              });
            }
          })
          .catch((error) => {
            console.log('error', error);
          });
      };
      //获取设备分类列表
      function geteqtClassList() {
        alleqtClass().then((res: any) => {
          eqtClassOptions.value = res.list;
        });
      }

      onMounted(() => {
        geteqtClassList();
        console.log(router.currentRoute.value.query.id + 'id');
        let type = router.currentRoute.value.query.type;
        if (type == 'edite') {
          let id = router.currentRoute.value.query.id;
          titleType.value = 'edite';
          getediteDetail(id);
        } else {
          formData.category_id = null;
          formData.disable = '1';
          titleType.value = 'add';
        }
      });

      //取消
      const cancel = () => {
        formRef.value.resetFields();
        router.push('/device/equipmentList');
      };
      return {
        spinning,
        selectChange,
        rules,
        isreload,
        tagsOk,
        sendIMGInfo,
        eqtClassOptions,
        getediteDetail,
        titleType,
        formRef,
        labelCol: { span: 10 },
        wrapperCol: { span: 14 },
        formData,
        handleOk,
        cancel,
        selectSubDevice,
      };
    },
  });
</script>
<style>
  .copypermis .ant-form-item-control-input-content {
    display: flex;
  }
</style>

<style lang="less" scoped>
  .main-eqt-wrapper {
    padding: 1rem;
    box-sizing: border-box;
    height: 100%;
    :deep(.ant-table-thead) tr td {
      background-color: #f7f9fd !important;
    }
    .img-subtile {
      font-size: 12px;
      margin-left: 5px;
    }
    .writeColor {
      color: #fff;
    }
    .zwf {
      width: 100%;
      height: 64px;
      background: transparent;
      display: block;
    }
    .flex-btn {
      background-color: #fff;
      width: 100%;
      display: flex;
      display: flex;
      justify-content: right;
      border-top: 1px solid #efefef;
      padding-right: 40px;
      height: 64px;
      align-items: center;
      box-sizing: border-box;
      position: absolute;
      bottom: 0px;
      left: 0px;
      .cancelBtn {
        margin-left: 16px;
      }
    }
    .copypermis {
      padding: 24px 24px 0px;
      box-sizing: border-box;
      background-color: #fff;
      height: 100%;
      position: relative;
      .form {
        display: flex;
        flex-wrap: wrap;
        :deep(.ant-form-item) {
          width: calc((100% - 48px) / 4);
          &:not(:nth-child(4n)) {
            margin-right: 16px;
          }
        }
      }
      .title {
        margin-bottom: 14px;
        font-weight: 600;
        font-size: 16px;
        box-sizing: border-box;
        position: relative;
        padding-left: 12px;
      }
      .befornline {
        &::before {
          content: '';
          width: 4px;
          height: 16px;
          background-color: #0663ff;
          position: absolute;
          top: 0px;
          bottom: 0px;
          margin: auto;
          left: 0px;
        }
      }
    }
  }
</style>
